package day8.homework;

import java.util.Scanner;


//b.通过线程模拟对同一个变量进行更改,
//   A线程睡眠10毫秒，对变量加1，B线程睡眠20毫秒对变量加1，持续3秒
//   查看多次运行的结果是否一致
public class B {
    static int i;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个变量:");
        i = sc.nextInt();
        DemoA demoA = new DemoA();
        DemoB demoB = new DemoB();
        demoA.setDaemon(true);
        demoB.setDaemon(true);

        Thread C = new Thread(() -> {
            try {
                Thread.sleep(300);
                System.out.println(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        C.start();
        demoA.start();
        demoB.start();

    }


    static class DemoA extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(10);
                    i++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
    }

    static class DemoB extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(20);
                    i++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
    }
}